//
//  CSNateMHomepyFolderSelectViewController.m
//  CairnStory
//  www.cairnstory.com
//
//  Created by saturna on 11. 4. 4..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CSNateMHomepyFolderSelectViewController.h"
#import "CSNateOAuthResult.h"
#import "CSNateRequest.h"
#import "CSXMLObject.h"
#import "CSUIAlertView.h"

#pragma mark -
#pragma mark CSNateMHomepyFolderSelectViewController (PrivateMethods)

@interface CSNateMHomepyFolderSelectViewController (PrivateMethods)

- (void)tapSelectButtonItem:(id)sender;
- (void)tapCancelButtonItem:(id)sender;

@end




#define kTableLineHeight 45


#pragma mark -
#pragma mark CSNateMHomepyFolderSelectViewController

@implementation CSNateMHomepyFolderSelectViewController


- (id)initWithNateOAuthResult:(CSNateOAuthResult*)oauthResult
				  andDelegate:(id<CSNateMHomepyFolderSelectViewDelegate,NSObject>)delegate
				  andMenuType:(CSNateMHomepyMenuType)menuType
{
	self = [super initWithNibName:NSStringFromClass([CSNateMHomepyFolderSelectViewController class]) bundle:nil];
	if (self == nil)
	{
		return self;
	}

	m_oauthResult = [oauthResult retain];
	m_delegate = [delegate retain];

	m_menuType = menuType;
	m_selectedIndex = -1;

	return self;
}



- (void)viewDidLoad
{
    [super viewDidLoad];

	UIBarButtonItem* barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Cancel"
																	  style:UIBarButtonItemStylePlain
																	 target:self
																	 action:@selector(tapCancelButtonItem:)];
	self.navigationItem.leftBarButtonItem = barButtonItem;
	[barButtonItem release];

	barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Select"
													 style:UIBarButtonItemStylePlain
													target:self
													action:@selector(tapSelectButtonItem:)];
	self.navigationItem.rightBarButtonItem = barButtonItem;
	[barButtonItem release];

	if (self.navigationItem.title == nil)
	{
		self.navigationItem.title = @"Select a Folder";
	}

	if (m_nateRequest != nil)
	{
		[m_nateRequest release];
		m_nateRequest = nil;
	}

	m_nateRequest = [[CSNateRequest alloc] initWithNateOAuthResult:m_oauthResult];
	m_nateRequest.nateTag = (NSUInteger)m_menuType;
	m_nateRequest.delegate = self;

	NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
	[params setObject:[NSString stringWithFormat:@"%d", m_menuType] forKey:@"menuType"];

	[m_nateRequest requestWithMethodName:CSNateRequestRetrieveFolderList
							   andParams:[params autorelease]];

	m_tableView.dataSource = self;
	m_tableView.delegate = self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}


- (void)dealloc
{
	[m_tableView release];
	[m_oauthResult release];
	[m_delegate release];
	[m_folderList release];

	if (m_nateRequest != nil)
	{
		[m_nateRequest release];
		m_nateRequest = nil;
	}

    [super dealloc];
}





#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return m_folderList == nil ? 0 : m_folderList.count;
}

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
	return kTableLineHeight;
}

// Customize the appearance of table view cells.
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
	static NSString* cellIdentifier = @"Cell";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
									   reuseIdentifier:cellIdentifier] autorelease];

		cell.selectionStyle = UITableViewCellSelectionStyleNone;
	}

	NSDictionary* menuDic = [m_folderList objectAtIndex:indexPath.row];
	cell.textLabel.text = [((NSDictionary*)[menuDic objectForKey:@"folderName"]) objectForKey:CSXMLObjectTextKey];
	cell.detailTextLabel.text = [((NSDictionary*)[menuDic objectForKey:@"folderOpenType"]) objectForKey:CSXMLObjectTextKey];

	cell.accessoryType = m_selectedIndex == indexPath.row
						? UITableViewCellAccessoryCheckmark
						: UITableViewCellAccessoryNone;

    return cell;
}






#pragma mark -
#pragma mark CSNateRequestDelegate


- (void)nateRequest:(CSNateRequest*)request
	didStartWithTag:(NSUInteger)nateTag
{
	// do nothing
}


- (void)nateRequest:(CSNateRequest*)request
  didSuccessWithTag:(NSUInteger)nateTag
	 withOutputType:(CSNateRequestOutputType)outputType
		 withResult:(id)result
{
	if (DEBUG) CSLog(@"===> %@", result);
	m_folderList = (NSArray*)[[((CSXMLObject*)result) subArrayWithElementPath:@"/ArrayOfFolder/Folder"] retain];

	[m_tableView reloadData];
}
/*
 폴더목록조회 결과
ArrayOfFolder =     {
	"#attributes" =         {
		xmlns = "http://schemas.datacontract.org/2004/07/Cy.Service.OpenCy.Entity";
		"xmlns:i" = "http://www.w3.org/2001/XMLSchema-instance";
	};
	Folder =         (
					  {
						  folderName =                 {
							  "#text" = "\Ub098\Uc758\Uadf8\Ub9bc";
						  };
						  folderNo =                 {
							  "#text" = 1;
						  };
						  folderOpen =                 {
							  "#text" = 4;
						  };
						  folderOpenType =                 {
							  "#text" = oneDegOpen;
						  };
						  id =                 {
							  "#text" = 56100753;
						  };
						  itemCount =                 {
							  "#text" = 0;
						  };
					  },
					  {
						  folderName =                 {
							  "#text" = "\Ub0b4 \Uc0ac\Uc9c4";
						  };
						  folderNo =                 {
							  "#text" = 3;
						  };
						  folderOpen =                 {
							  "#text" = 2;
						  };
						  folderOpenType =                 {
							  "#text" = allOpen;
						  };
						  id =                 {
							  "#text" = 56100753;
						  };
						  itemCount =                 {
							  "#text" = 0;
						  };
					  }
					  );
};
*/
- (void)nateRequest:(CSNateRequest*)request
	 didFailWithTag:(NSUInteger)nateTag
		withMessage:(NSString*)alertMessage
		  withError:(NSError*)error
{
	if (DEBUG) CSLog(@"===> %@", error);
	CSUIAlertView* alertView = [[CSUIAlertView alloc]
								initAlertWithTitle:@"CairnStory"
								message:alertMessage
								target:nil
								action:nil];
	[alertView show];
	[alertView autorelease];
}

- (void)nateRequest:(CSNateRequest*)request
   didFinishWithTag:(NSUInteger)nateTag
{
	if (m_nateRequest != nil)
	{
		[m_nateRequest release];
		m_nateRequest = nil;
	}
}








#pragma mark -
#pragma mark UITableViewDelegate

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
	UITableViewCell* cell;

	// 한개만 체크되도록 한다.
	for (int i=0; i<[tableView numberOfRowsInSection:indexPath.section]; i++)
	{
		if (i == indexPath.row)
		{
			cell = [tableView cellForRowAtIndexPath:indexPath];
			cell.accessoryType = UITableViewCellAccessoryCheckmark;
			m_selectedIndex = i;
		}
		else
		{
			cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:indexPath.section]];
			cell.accessoryType = UITableViewCellAccessoryNone;
		}
	}

	[tableView cellForRowAtIndexPath:indexPath].selected = NO;
}




#pragma mark -
#pragma mark CSNateMHomepyFolderSelectViewController (PrivateMethods)

- (void)tapSelectButtonItem:(id)sender
{
	if (m_folderList == nil || m_selectedIndex < 0)
	{
		[self tapCancelButtonItem:sender];
		return;
	}

	[m_delegate folderSelectViewController:self
					 didSelectWithMenuType:m_menuType
							withFolderInfo:[m_folderList objectAtIndex:m_selectedIndex]];
}

- (void)tapCancelButtonItem:(id)sender
{
	[m_delegate folderSelectViewController:self
					 didCancelWithMenuType:m_menuType];
}


@end
